//
// Unihan Input Method
//
// Copyright © 2002-2007 Sun Wah Linux Ltd.
//
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 2.1 of the
// License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
// USA
//
// $Id: utils.c 757 2007-05-10 08:19:31Z roger $
//

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <unihan_im.h>

#include "utils.h"

#define BUFFER_SIZE 1024

static void filecp(const char *dest, const char *orig);

void
confirm_user_data(UnihanIM *uim)
{
	char filename[256];
	char *p = (char *)uim->imUserData + strlen(FREQ_DATA_DIR);
	char *point = strchr(p, '.');
	struct stat buf;

	p++;
	*point = 0;
	sprintf(filename, "%s/%s/%s.%s", get_home_dir(), ".unihan2", p, "frq");
	if (access(filename, F_OK) == -1) {
		char origfilename[256];

		sprintf(origfilename, "%s/%s.%s",
				FREQ_DATA_DIR,
				p,
				"frq");
		filecp(filename, origfilename);
	}
	*point = '.';
}

char *
get_home_dir()
{
	return getenv("HOME");
}

static void
filecp(const char *dest, const char *orig)
{
		 
	int from_fd,to_fd;
	int bytes_read,bytes_write;
	char buffer[BUFFER_SIZE];
	char *ptr;

	if((from_fd=open(orig, O_RDONLY)) == -1) {
#if DEBUG
		fprintf(stderr,"Open orig file %s Error : %s\n", orig, strerror(errno));
#endif
		return; 
	}
	
	if((to_fd=open(dest, O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR)) == -1) {
#if DEBUG
		fprintf(stderr,"Open dest file%s Error : %s\n", dest, strerror(errno));
#endif
		return;
	}
	
	while(bytes_read = read(from_fd, buffer, BUFFER_SIZE)) {
		if((bytes_read == -1) && (errno != EINTR))
			break;
		else if(bytes_read > 0) {
			ptr=buffer;
			while(bytes_write = write(to_fd, ptr, bytes_read)) {
				if((bytes_write == -1) && (errno != EINTR))
					break;
				else if(bytes_write == bytes_read)
					break;
				else if(bytes_write > 0) {
					ptr += bytes_write;
					bytes_read -= bytes_write;
				}
			}
			if(bytes_write == -1)
				break;
		}
	}
	close(from_fd);
	close(to_fd);
	return;
}

// vi:ts=4:nowrap:cin:expandtab
